"""
列标识对话框
允许用户选择要标记的列，被标记的列将被放置在最前面
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QListWidget, 
                              QListWidgetItem, QPushButton, QLabel, QCheckBox,
                              QDialogButtonBox, QGroupBox, QScrollArea, QWidget, QLineEdit)
from PySide6.QtCore import Qt, Signal
from typing import List, Set


class ColumnMarkerDialog(QDialog):
    """列标识对话框"""
    
    def __init__(self, headers: List[str], marked_columns: Set[int], parent=None):
        super().__init__(parent)
        self.headers = headers
        self.marked_columns = marked_columns.copy()
        self._checkbox_map = {}  # header_index -> checkbox
        self._setup_ui()
        
    def _setup_ui(self):
        """设置UI"""
        self.setWindowTitle("列标识设置")
        self.setModal(True)
        self.setMinimumSize(400, 500)
        
        layout = QVBoxLayout(self)
        
        # 说明标签
        info_label = QLabel("选择要标记的列。被标记的列将被放置在最前面并冻结显示。支持搜索列名快速定位。")
        info_label.setWordWrap(True)
        layout.addWidget(info_label)
        
        # 搜索框
        search_layout = QHBoxLayout()
        search_label = QLabel("搜索:")
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("输入列名关键字...")
        self.search_edit.textChanged.connect(self._on_search_changed)
        search_layout.addWidget(search_label)
        search_layout.addWidget(self.search_edit)
        layout.addLayout(search_layout)
        
        # 创建滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_widget = QWidget()
        self.scroll_layout = QVBoxLayout(self.scroll_widget)
        
        # 列选择区域
        self.group_box = QGroupBox("选择要标记的列")
        self.group_layout = QVBoxLayout(self.group_box)
        
        # 全选/取消全选按钮
        select_buttons_layout = QHBoxLayout()
        select_all_btn = QPushButton("全选")
        select_all_btn.clicked.connect(self._select_all)
        deselect_all_btn = QPushButton("取消全选")
        deselect_all_btn.clicked.connect(self._deselect_all)
        select_buttons_layout.addWidget(select_all_btn)
        select_buttons_layout.addWidget(deselect_all_btn)
        select_buttons_layout.addStretch()
        self.group_layout.addLayout(select_buttons_layout)
        
        # 列复选框列表
        self.column_checkboxes = []
        self._checkbox_map.clear()
        for i, header in enumerate(self.headers):
            checkbox = QCheckBox(f"{i+1}. {header}")
            checkbox.setChecked(i in self.marked_columns)
            checkbox.stateChanged.connect(self._on_checkbox_changed)
            self.column_checkboxes.append(checkbox)
            self._checkbox_map[i] = checkbox
            self.group_layout.addWidget(checkbox)
        
        self.scroll_layout.addWidget(self.group_box)
        self.scroll_area.setWidget(self.scroll_widget)
        layout.addWidget(self.scroll_area)
        
        # 按钮区域
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
        
    def _select_all(self):
        """全选当前过滤结果"""
        for checkbox in self.column_checkboxes:
            if checkbox.isVisible():
                checkbox.setChecked(True)
        
    def _deselect_all(self):
        """取消全选当前过滤结果"""
        for checkbox in self.column_checkboxes:
            if checkbox.isVisible():
                checkbox.setChecked(False)
        
    def _on_checkbox_changed(self):
        """复选框状态改变时的处理"""
        self.marked_columns.clear()
        for i, checkbox in enumerate(self.column_checkboxes):
            if checkbox.isChecked():
                self.marked_columns.add(i)
        
    def _on_search_changed(self):
        """搜索框内容变化时过滤复选框"""
        keyword = self.search_edit.text().strip().lower()
        for i, header in enumerate(self.headers):
            checkbox = self._checkbox_map[i]
            if not keyword or keyword in header.lower():
                checkbox.setVisible(True)
            else:
                checkbox.setVisible(False)
        # 可选：自动展开/收起分组
        self.group_box.setTitle(f"选择要标记的列（共{sum(cb.isVisible() for cb in self.column_checkboxes)}项）")
        
    def get_marked_columns(self) -> Set[int]:
        """获取被标记的列索引集合"""
        return self.marked_columns.copy()
        
    @staticmethod
    def show_dialog(headers: List[str], marked_columns: Set[int], parent=None) -> tuple[bool, Set[int]]:
        """显示对话框并返回结果"""
        dialog = ColumnMarkerDialog(headers, marked_columns, parent)
        if dialog.exec() == QDialog.Accepted:
            return True, dialog.get_marked_columns()
        return False, marked_columns 